package com.translate;

/**
 * @author by Administrator on 2018/1/17.
 */
public class XMLEncoder {
    private static final String[] XML_CODE = new String[256];

    static {
        // Special characters
        XML_CODE['\''] = "&apos;";
        XML_CODE['\"'] = "&quot;";
        // double quote
        XML_CODE['&'] = "&amp;";
        // ampersand
        XML_CODE['<'] = "&lt;";
        // lower than
        XML_CODE['>'] = "&gt;";
        XML_CODE['\b'] = "&#x0020;";
        XML_CODE['\r'] = "&#x000A;";
        XML_CODE['\n'] = "&#x000D;";
        XML_CODE['\t'] = "&#x0009;";
        XML_CODE['\f'] = " ";
    }

    /**
     * <p>
     * Encode the given text into xml.
     * </p>
     *
     * @param string the text to encode
     * @return the encoded string
     */
    public static String encode(String string) {
        if (org.springframework.util.StringUtils.isEmpty(string)) {
            return "";
        }
        int n = string.length();
        char character;
        String xmlchar;
        StringBuffer buffer = new StringBuffer();
        // loop over all the characters of the String.
        for (int i = 0; i < n; i++) {
            character = string.charAt(i);
            // the xmlcode of these characters are added to a StringBuffer one by one
            try {
                xmlchar = XML_CODE[character];
                if (xmlchar == null) {
                    buffer.append(character);
                } else {
                    buffer.append(XML_CODE[character]);
                }
            } catch (ArrayIndexOutOfBoundsException aioobe) {
                buffer.append(character);
            }
        }
        return buffer.toString();
    }
}
